//
//  NKAccountViewController.m
//  NewKY
//
//  Created by Dee on 2016/11/12.
//  Copyright © 2016年 Dee. All rights reserved.
//

#import "NKAccountViewController.h"
#import "CZAdditions.h"
#import "NKTableViewCell.h"
#import <Masonry.h>
#import "NKModel.h"
#import "YzPickerView.h"
#import <UIImageView+WebCache.h>

#define USERINFO_CELL @"USERINFO_CELL"

@interface NKAccountViewController ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

 /*---- 数据源数组 -----*/
@property(nonatomic,copy)NSArray *modelArr;
 /*---- 记录头像 -----*/
@property(nonatomic,weak)UIImageView *headImageView;
/*---- label记录 -----*/
@property(nonatomic,weak)UILabel  *detailLabel;
/*---- 记录 -----*/
@property(nonatomic,weak)UITableView *tableView;

@end

@implementation NKAccountViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationController.automaticallyAdjustsScrollViewInsets = NO;
     /*---- 设置界面 -----*/
    [self setupUI];

}

#pragma mark 初始化界面
/*
  搭建界面
**/
-(void)setupUI{
    
    self.navigationItem.title = @"个人信息";
    self.navigationController.navigationBar.barTintColor = [UIColor cz_colorWithHex:0x20c6c6];
     /*---- 添加TableView -----*/
    UITableView *tab = [[UITableView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:tab];
    self.tableView = tab;
    tab.dataSource = self;
    tab.delegate = self;
    [tab registerClass:[NKTableViewCell class] forCellReuseIdentifier:USERINFO_CELL];

    //================== 设置 HeaderView =================//
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 180)];
    
    NSURL *url = [NSURL URLWithString:@"http://imgsrc.baidu.com/forum/w=580/sign=66a34e373b6d55fbc5c6762e5d234f40/6aac4d086e061d954a4f15d17df40ad163d9ca7f.jpg"];
    
//    UIImage *img = [UIImage imageNamed:@"An_lufei"];
    
    UIImageView *imgV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 180)];
    [imgV sd_setImageWithURL:url];
    imgV.contentMode = UIViewContentModeScaleAspectFill;
    headerView.clipsToBounds = YES;
    [headerView addSubview:imgV];
    tab.tableHeaderView = headerView;
    
     /*---- 设置FooterView -----*/
    UIView * FooterView = [[UIView alloc]init];
    tab.backgroundColor = [UIColor colorWithRed:245.0/255 green:245.0/255 blue:245.0/255 alpha:1.0];
    tab.tableFooterView = FooterView;
    
    //================== 设置圆形图像 =================//
    
    UIImage *headImg;
     /*---- 判断沙盒中是否有缓存 -----*/
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"avatar.png"];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath]) {
        
         headImg = [[UIImage alloc]initWithContentsOfFile:fullPath];
    }else{
        
        headImg =[UIImage imageNamed:@"An_head"];
    }
    
    UIImageView *headImgV = [[UIImageView alloc]initWithImage:headImg];
    
     CGFloat headImgVWH = 80.0;

    /*---- 头像添加点击手势 -----*/
    headImgV.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changImage)];
    [headImgV addGestureRecognizer:tap];
    
    /*---- 设置圆角 -----*/
    headImgV.layer.cornerRadius = 40;
    headImgV.clipsToBounds = YES;
    headImgV.layer.borderWidth = 3.0f;
    headImgV.layer.borderColor = [UIColor whiteColor].CGColor;
    [tab addSubview:headImgV];
    self.headImageView = headImgV;
    
    [headImgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(tab.mas_centerX);
        make.centerY.mas_equalTo(headerView.mas_centerY).offset(18);
        make.width.height.mas_equalTo(headImgVWH);
    }];

}

#pragma mark -点击头像响应事件

-(void)changImage{
    
    UIAlertController *alert = [[UIAlertController alloc]init];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
     
        BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
        if (!isCamera) {
            UIAlertController *camera = [UIAlertController alertControllerWithTitle:@"未检测到摄像头" message:nil preferredStyle:UIAlertControllerStyleAlert];
             [camera addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]];
            
            [self presentViewController:camera animated:YES completion:nil];
        }else{
        
        /*---- 没有摄像头的其他情况 访问相机 -----*/
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc ]init];
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        
        [self presentViewController:imagePicker animated:YES completion:nil];
        }}]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"从相册获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UIImagePickerController *imgPicker = [[UIImagePickerController alloc]init];
         /*---- 设置代理 -----*/
        imgPicker.delegate = self;
        imgPicker.allowsEditing = YES;
        
        [self presentViewController:imgPicker animated:YES completion:nil];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark  获取相册 的代理方法

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    [picker dismissViewControllerAnimated:YES completion:^{
        /*---- 拿到用户选择的原始图片 -----*/
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        [self saveImage:image withName:@"avatar.png"];
        
         /*---- 赋值 -----*/
        [self.headImageView setImage:image];
        
        [[self getLeftViewController].headerView setBtnImage];
        
    }];

}

 /*---- 保存图片到沙盒 -----*/
-(void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName{
    
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 1);
     /*---- 获取沙盒路径 -----*/
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
     /*---- 将图片写入 -----*/
    [imageData writeToFile:fullPath atomically:YES];
    
}

#pragma mark - UITableViewDataSource

 /*---- 数据源 -----*/

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.modelArr.count;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NKTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:USERINFO_CELL forIndexPath:indexPath];
     /*---- 显示右侧的箭头 -----*/
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    NKModel *model = self.modelArr[indexPath.row];
    cell.imageView.image = [UIImage imageNamed:model.icon];
    cell.textLabel.text = model.title;
    cell.height = 40;
    
    cell.label.text = [self getUserWithTag:indexPath];
    
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    /*---- 取消选中状态 -----*/
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
     /*---- 判断点击的行数 -----*/
    switch (indexPath.row) {
        case 0:
             /*---- 名字 -----*/
            [self setName:indexPath];
            break;
        case 1:
             /*---- 性别 -----*/
            [self setGender:indexPath];
            break;
        case 2:
             /*---- 证件号码 -----*/
            [self setCertificates:indexPath];
            break;
        case 3:
             /*---- 联系方式 -----*/
            [self setTelephone:indexPath];
            break;
        case 4:
             /*---- 身高 -----*/
            [self setHeightWithIndex:indexPath];
            break;
        case 5:
             /*---- 体重 -----*/
            [self setWeightWithIndexPath:indexPath];
            break;
        case 6:
             /*---- 籍贯 -----*/
            [self setPlaceOfOrigin:indexPath];
            
            break;
        case 7:
             /*---- 常居地 -----*/
            [self setHabitat:indexPath];
            
            break;

        default:
            break;
    }

}

#pragma mark - 点击cell修改个人信息

 //================== 修改名字 =================//
-(void)setName:(NSIndexPath *)index{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改姓名" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        BOOL result = [NKAccountViewController validateNickname:alert.textFields.firstObject.text];
        if (result) {
            /*---- 给label  赋值 -----*/
            NKTableViewCell *cell = [self.tableView cellForRowAtIndexPath:index];
            
            cell.label.text =  alert.textFields.firstObject.text;
            
            //保存数据
            [self saveUserWith:alert.textFields.firstObject.text :index];
            
            [[self getLeftViewController].headerView.registerButton setTitle:alert.textFields.firstObject.text forState:UIControlStateNormal];
            
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSString *phone = [userDefaults objectForKey:@"NOW_USER_PHONE"];
            [userDefaults setObject:alert.textFields.firstObject.text forKey:[@"name="stringByAppendingString:phone]];
            
        }else{
            
            UIAlertController *err = [UIAlertController alertControllerWithTitle:@"输入格式错误" message:@"提示:请输入纯字母" preferredStyle:UIAlertControllerStyleAlert];
            [err addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:NULL]];
            [self presentViewController:err animated:YES completion:nil];
        }
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL]];
    
     /*---- 添加文本框 -----*/
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入姓名";
    }];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

//================== 修改性别 =================//
-(void)setGender:(NSIndexPath *)index{
    UIAlertController *alert = [[UIAlertController alloc]init];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"女");
        /*---- 给label  赋值 -----*/
        NKTableViewCell *cell = [self.tableView cellForRowAtIndexPath:index];
    
        cell.label.text = action.title;
        
         /*---- 保存 -----*/
        [self saveUserWith:action.title :index];
        
    }]];
   
    [alert addAction:[UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"男");
        /*---- 给label  赋值 -----*/
        NKTableViewCell *cell = [self.tableView cellForRowAtIndexPath:index];
        
        cell.label.text = action.title;
         /*---- 保存 -----*/
         [self saveUserWith:action.title :index];
        
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

//================== 修改证件 =================//
-(void)setCertificates:(NSIndexPath *)index{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改证件号码" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
       
        BOOL result = [NKAccountViewController judgeIdentityStringValid:alert.textFields.firstObject.text];
        if (result) {
             /*---- 如果值是正确的,就赋值 -----*/
            NKTableViewCell *cell = [self.tableView cellForRowAtIndexPath:index];
           cell.label.text =  alert.textFields.firstObject.text;
            /*---- 保存 -----*/
            [self saveUserWith:alert.textFields.firstObject.text :index];
            
        }else{
       
            UIAlertController *err = [UIAlertController alertControllerWithTitle:@"输入信息错误" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [err addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:NULL]];
            [self presentViewController:err animated:YES completion:nil];
        }
        
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL]];
    
    /*---- 添加文本框 -----*/
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        textField.placeholder = @"请输入证件号";
    }];
    
    [self presentViewController:alert animated:YES completion:nil];
}

//================== 修改联系方式 =================//
-(void)setTelephone:(NSIndexPath *)index{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改联系方式" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        BOOL result = [NKAccountViewController valiMobile:alert.textFields.firstObject.text];
        if (result) {
            /*---- 如果值是正确的,就赋值 -----*/
            NKTableViewCell *cell = [self.tableView cellForRowAtIndexPath:index];
            cell.label.text =  alert.textFields.firstObject.text;
            
            /*---- 保存 -----*/
            [self saveUserWith:alert.textFields.firstObject.text :index];
            
        }else{
            UIAlertController *err = [UIAlertController alertControllerWithTitle:@"输入错误" message:nil preferredStyle:UIAlertControllerStyleAlert];
           
            [err addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL]];
            
            [self presentViewController:err animated:YES completion:nil];
        }
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL]];
    
    /*---- 添加文本框 -----*/
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        textField.placeholder = @"请输入联系方式";
    }];
    
    [self presentViewController:alert animated:YES completion:nil];
}

 /*---- 修改身高 -----*/
-(void)setHeightWithIndex:(NSIndexPath *)index{
    
    YzPickerView *picker = [[YzPickerView alloc]initWithIsCity:NO];
    
    [picker show];
    
    [picker setPickerViewValueChangeBlock:^(NSString *str) {
        NKTableViewCell *cell = [self.tableView cellForRowAtIndexPath:index];
        NSString *height = [str stringByAppendingString:@"cm"];
        cell.label.text = height;
        
        /*---- 保存 -----*/
        [self saveUserWith:height :index];
        
    }];
    
    
}

 /*---- 修改体重 -----*/
-(void)setWeightWithIndexPath:(NSIndexPath *)index{
    
    YzPickerView *picker = [[YzPickerView alloc]initWithIsCity:NO];
    
    [picker show];
    
    [picker setPickerViewValueChangeBlock:^(NSString *str) {
        NKTableViewCell *cell = [self.tableView cellForRowAtIndexPath:index];
         NSString *weight = [str stringByAppendingString:@"kg"];
        cell.label.text = weight;
        /*---- 保存 -----*/
        [self saveUserWith:weight :index];
    }];
    
}

 /*---- 修改籍贯 -----*/
-(void)setPlaceOfOrigin:(NSIndexPath *)index{
    
    YzPickerView *picker = [[YzPickerView alloc]initWithIsCity:YES];
    
    [picker show];
    
    [picker setPickerViewValueChangeBlock:^(NSString *str) {
        NKTableViewCell *cell = [self.tableView cellForRowAtIndexPath:index];
        cell.label.text =  str;
        /*---- 保存 -----*/
        [self saveUserWith:str :index];
        
    }];
    
}

 /*---- 修改常居地 -----*/
-(void)setHabitat:(NSIndexPath *)index{
    
    [self setPlaceOfOrigin:index];
}

#pragma mark  判断手机号码和证件号码是否正确

/*---- 判断手机号码是否合法 -----*/
//判断手机号码格式是否正确
+ (BOOL)valiMobile:(NSString *)mobile
{
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11)
    {
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}

//================== 身份证正则算法 =================//
+ (BOOL)judgeIdentityStringValid:(NSString *)identityString {
    
    if (identityString.length != 18) return NO;
    // 正则表达式判断基本 身份证号是否满足格式
    NSString *regex2 = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
    NSPredicate *identityStringPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    //如果通过该验证，说明身份证格式正确，但准确性还需计算
    if(![identityStringPredicate evaluateWithObject:identityString]) return NO;
    
    //** 开始进行校验 *//
    
    //将前17位加权因子保存在数组里
    NSArray *idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
    
    //这是除以11后，可能产生的11位余数、验证码，也保存成数组
    NSArray *idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
    
    //用来保存前17位各自乖以加权因子后的总和
    NSInteger idCardWiSum = 0;
    for(int i = 0;i < 17;i++) {
        NSInteger subStrIndex = [[identityString substringWithRange:NSMakeRange(i, 1)] integerValue];
        NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
        idCardWiSum+= subStrIndex * idCardWiIndex;
    }
    
    //计算出校验码所在数组的位置
    NSInteger idCardMod=idCardWiSum%11;
    //得到最后一位身份证号码
    NSString *idCardLast= [identityString substringWithRange:NSMakeRange(17, 1)];
    //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
    if(idCardMod==2) {
        if(![idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"]) {
            return NO;
        }
    }
    else{
        //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
        if(![idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]]) {
            return NO;
        }
    }
    return YES;
}

//================== 昵称正则算法 =================//
//昵称
+ (BOOL) validateNickname:(NSString *)nickname
{
    NSString *nicknameRegex = @"[a-zA-Z]*";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    return [passWordPredicate evaluateWithObject:nickname];

}


 /*---- 保存到用户偏好设置 -----*/
-(NSUserDefaults *)saveUserInfo{
    
    return[NSUserDefaults standardUserDefaults];
    
}



#pragma mark  - 保存用户信息
/**
 
 @param tag tag
 @return tag=phone
 */
-(NSString *)getUserWithTag:(NSIndexPath *)indexpath{
    
    
    NSString *phone = [[self saveUserInfo]objectForKey:@"NOW_USER_PHONE"];
    NSString *nameStr = [[self saveUserInfo]objectForKey:[NSString stringWithFormat:@"%ld=%@",(long)indexpath.row,phone]];
    
    return nameStr;
}

//存储
-(void)saveUserWith:(NSString *)saveData :(NSIndexPath*)indexpath{
    NSString *phone = [[self saveUserInfo]objectForKey:@"NOW_USER_PHONE"];
    
    NSString *keyStr= [NSString stringWithFormat:@"%ld=%@",(long)indexpath.row,phone];
    [[self saveUserInfo]setObject:saveData forKey:keyStr];
    
}



// ---- 懒加载 -----
-(NSArray *)modelArr{
    
    if(_modelArr == nil){
        
    NSArray *dictArr = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"my.plist" ofType:nil]];
       
         NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:dictArr.count];
        
        for (NSDictionary *dict in dictArr) {
            
            [arrM addObject:[NKModel modelWithDict:dict]];
        }
        _modelArr = arrM;
    }
    return _modelArr;
    
}

@end
